import base64 from '@/ext/base64.min.js'
const Base64 = base64.Base64
const baseUrl = 'https://www.oss.talentmatch.top'
import http from '@/ext/http.js'

export default class UpLoadImg {
	
	getPolicyBase64() {
		const policyText = {
			'expiration': this.Expiration,
			"conditions": [
				["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
			]
		};

		const policyBase64 = Base64.encode(JSON.stringify(policyText));
		return policyBase64;
	}

	getImage() {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1,
				success: res => {
					const tempFilePaths = res.tempFilePaths[0]
					resolve(tempFilePaths)
				},
				fail: () => {
					this.$Toast('请上传图片')
					reject()
				}
			})
		})
	}
	
	uploadFile() {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: this.host,
				filePath: this.fileUrl,
				name: 'file',
				formData:{
					name: this.fileUrl,
					key: `${this.dir + '/'+ this.aliyunFileKey}`,
					policy: this.policy,
					OSSAccessKeyId: this.AccessKeyId,
					signature: this.signature,
					// 'x-oss-security-token': this.SecurityToken,
					success_action_status: '200',
				},
				success:(res) => {
					if (res.errMsg == 'uploadFile:ok') {
						resolve({
							fileName: `${baseUrl}/${this.dir}/${this.aliyunFileKey}`
						})
					} else {
						reject()
					}
				},
				fail:(err) => {
					reject()
				}
			})
		})
	}

	getOssToken() {
		return this.getImage().then(res => {
			this.fileUrl = res
			this.aliyunFileKey = new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
			return http.mgHttp('/aliyun/oss/policy', {})
		}).then(res => {
			const result = res.result
			this.AccessKeyId = result.accessKeyId
			// this.AccessKeySecret = result.AccessKeySecret
			this.host = result.host
			this.policy = result.policy
			this.signature = result.signature
			this.dir = result.dir
			return this.uploadFile()
		})
	}
}
